<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Models\WechatUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Models\UserToken;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Illuminate\Http\JsonResponse;

class AuthController extends Controller
{
    public function login(Request $request): JsonResponse
    {
        $code = $request->input('code');

        if (empty($code)) {
            Log::warning('登录失败：缺少code参数');
            return response()->json(['message' => '缺少code参数'], 422);
        }

        try {
            $user = $this->getUserFromWechat($code);
            $token = $this->generateToken($user);

            return response()->json([
                'token' => $token,
                'user' => $this->getUserResponseData($user)
            ]);
        } catch (\Exception $e) {
            Log::error('登录过程发生异常', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json(['message' => '服务器错误，请稍后重试'], 500);
        }
    }

    private function getUserFromWechat($code)
    {
        $appid = config('services.wechat.mini_program.app_id');
        $secret = config('services.wechat.mini_program.app_secret');

        $response = Http::withoutVerifying()
            ->get('https://api.weixin.qq.com/sns/jscode2session', [
                'appid' => $appid,
                'secret' => $secret,
                'js_code' => $code,
                'grant_type' => 'authorization_code'
            ]);

        $result = $response->json();

        if (isset($result['errcode']) && $result['errcode'] != 0) {
            throw new \Exception($result['errmsg'] ?? '微信登录接口错误');
        }

        return WechatUser::updateOrCreate(
            ['openid' => $result['openid']],
            ['session_key' => $result['session_key']]
        );
    }

    private function generateToken($user)
    {
        $token = Str::random(64); // 或者使用 JWT 库生成更复杂的 Token
        UserToken::create([
            'wechat_user_id' => $user->id,
            'token' => $token,
            'expired_at' => now()->addMinutes(20),
        ]);

        return $token;
    }

    private function getUserResponseData($user)
    {
        return [
            'id' => $user->id,
            'openid' => $user->openid,
            // 'session_key' => $user->session_key, // 不返回敏感信息
            'nickname' => $user->nickname,
            'avatar' => $user->avatar,
            'gender' => $user->gender,
            'country' => $user->country,
            'province' => $user->province,
            'city' => $user->city,
            'created_at' => $user->created_at,
            'updated_at' => $user->updated_at,
        ];
    }


    public function verifyToken(Request $request)
    {
        try {
            $token = str_replace('Bearer ', '', $request->header('Authorization'));

            Log::info('Token验证请求', [
                'token' => $token,
                'ip' => $request->ip()
            ]);

            if (empty($token)) {
                Log::warning('Token验证失败：未提供token');
                return response()->json(['valid' => false, 'message' => '未提供token'], 401);
            }

            $userToken = UserToken::where('token', $token)
                ->where('expired_at', '>', Carbon::now())
                ->first();

            if (!$userToken) {
                Log::warning('Token验证失败：token无效或已过期', [
                    'token' => $token
                ]);
                return response()->json(['valid' => false, 'message' => 'token无效或已过期'], 401);
            }

            Log::info('Token验证成功', [
                'user_id' => $userToken->wechat_user_id,
                'token' => $token
            ]);

            return response()->json([
                'valid' => true,
                'message' => 'token有效',
                'expires_in' => Carbon::now()->diffInSeconds($userToken->expired_at)
            ]);
        } catch (\Exception $e) {
            Log::error('Token验证过程发生异常', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'valid' => false,
                'message' => '服务器错误'
            ], 500);
        }
    }
}
